<script setup lang="ts">

import {constantStore} from "~/stores/constantStore";
import {getProjectList} from "~/api/projectApi";
import {getCommodityCategoryList, getCommodityList} from "~/api/commodityApi";
import {successCode} from "~/api/base/http";
import MySelect from "~/components/constant/mySelect.vue";
import CommodityInfo from "~/components/shop/commodityInfo.vue";
import {ref} from "vue"
import ScrollBox from "~/components/constant/scrollBox.vue";
import MoveTo from "~/components/constant/moveTo.vue";
import {addShoppingApi} from "~/api/orderApi";
import {error, success} from "~/utils/myMessage";

constantStore().setCurrentActivityTab("shop");
constantStore().setShoppingIconShow(true);
const route = useRoute()

const id = route.params.id

useHead({
  title: constantStore().webTitle + ' -- 商城',
  meta: [
    {name: 'keywords', content: constantStore().webKeywords},
    {name: 'description', content: constantStore().webDescription}
  ],
})

onMounted(() => {
  userInfoStore().initShopping()
})

onBeforeRouteLeave(() => {
  constantStore().setShoppingIconShow(false);
})

let {data: projectRes} = await useAsyncData('getProjectList', () => getProjectList());
const project = ref(constantStore().parseRes(projectRes));

let thisTabProjectId = ref();

let categoryId = ref();

let name = ref();
let initPageSize = 24;
let pageObj = ref({
  currentPage: 1,
  pageSize: initPageSize,
  totalPages: 0,
  totalCount: 0,
  first: false,
  last: false,
})

const commodity = ref();
const commodityList = ref([]);

const commodityCategoryList = ref();
const commodityCategorySelect = ref();

if (project.value && project.value.length > 0) {
  let projectItem = project.value[0];
  if (id === null || id === undefined || id === "") {
    thisTabProjectId.value = projectItem.id;
  } else {
    thisTabProjectId.value = id;
  }
  constantStore().setShoppingThisTabProjectId(thisTabProjectId.value);

  let {data: commodityRes} = await useAsyncData('getCommodityList', () => getCommodityList(pageObj.value.currentPage, pageObj.value.pageSize, thisTabProjectId.value, categoryId.value, name.value));
  commodity.value = constantStore().parseRes(commodityRes);
  constantStore().copyPage(pageObj, commodity.value);
  commodityList.value = commodity.value.content;

  let {data: commodityCategoryRes} = await useAsyncData('getCommodityCategoryList', () => getCommodityCategoryList(thisTabProjectId.value));
  commodityCategoryList.value = constantStore().parseRes(commodityCategoryRes);
  commodityCategorySelect.value = constantStore().listToSelect(commodityCategoryList.value, "name", "id");
}


function changeProject(projectItem) {
  if (thisTabProjectId.value === projectItem.id) {
    return;
  }
  thisTabProjectId.value = projectItem.id;
  constantStore().setShoppingThisTabProjectId(thisTabProjectId.value);
  pageObj.value.currentPage = 1;
  pageObj.value.pageSize = initPageSize;
  categoryId.value = "";
  name.value = "";
  getCommodityCategoryList(thisTabProjectId.value).then(res => {
    if (res.code === successCode) {
      commodityCategoryList.value = res.data;
      commodityCategorySelect.value = constantStore().listToSelect(commodityCategoryList.value, "name", "id")
    }
  })

  getCommodityList(pageObj.value.currentPage, pageObj.value.pageSize, thisTabProjectId.value, categoryId.value, name.value).then(res => {
    if (successCode === res.code) {
      constantStore().copyPage(pageObj, res.data);
      commodityList.value = res.data.content;
    }
  })
}

/**
 * 分页搜索相关
 */
function doSearch() {
  getCommodityList(pageObj.value.currentPage, pageObj.value.pageSize, thisTabProjectId.value, categoryId.value, name.value).then(res => {
    if (successCode === res.code) {
      constantStore().copyPage(pageObj, res.data);
      commodityList.value = res.data.content;
    }
  })
}

const loading = ref(false);

async function loadingMore() {
  if (pageObj.value.last) {
    return;
  }
  loading.value = true;
  getCommodityList(pageObj.value.currentPage, pageObj.value.pageSize, thisTabProjectId.value, categoryId.value, name.value).then(res => {
    if (successCode === res.code) {
      constantStore().copyPage(pageObj, res.data);
      commodityList.value = commodityList.value.concat(res.data.content);
    }
    loading.value = false;
  })
}

function changeSelect() {
  pageObj.value.currentPage = 1;
  doSearch();
}

function handleSizeChange() {
  doSearch()
}

async function handleSizeChangeScroll() {
  pageObj.value.currentPage += 1;
  await loadingMore()
}

function handleCurrentChange() {
  doSearch()
}

/**
 * 购物车相关
 */
let moveToShow = ref(false);

function addShopping(info) {
  if (!userInfoStore().checkUserLogin()) {
    moveToShow.value = true;
    return;
  }

  let orderInfo = copyInfo(info);
  addShoppingApi(orderInfo).then(res => {
    if (res.code === successCode) {
      let order = orderInfo;
      order.id = res.data.id;
      userInfoStore().addShopping(order);
      success(res.message)
    } else {
      error(res.message);
    }
  })
}

function buyThisCommodity(info) {
  if (!userInfoStore().checkUserLogin()) {
    moveToShow.value = true;
    return;
  }
  copyInfo(info);
}

function copyInfo(info) {
  let orderInfo = {
    id: "",
    commodityId: "",
    projectId: "",
    count: 1,
    level: 1,
    multiplier: 1,
    isBluePic: false,
    money: "0.00",
    commodity: {},
  }
  orderInfo.projectId = thisTabProjectId.value;
  orderInfo.commodityId = info.id
  orderInfo.count = info.number
  orderInfo.level = info.level
  orderInfo.multiplier = info.multiplier
  orderInfo.isBluePic = info.isBluePic
  orderInfo.money = info.nowPrice
  orderInfo.commodity = info.commodity;
  return orderInfo;
}

</script>

<template>
  <div class="shop-box">
    <div class="shop-tab">
      <template v-for="(item, index) in project">
        <div :class="thisTabProjectId===item.id?'shop-tab-item shop-tab-item-active':'shop-tab-item'"
             @click="changeProject(item)">
          {{ item.name }}
        </div>
      </template>
    </div>
    <div class="shop-content">
      <div class="commodity-search-box">
        <div class="commodity-search-item">
          <my-select v-model="categoryId" placeholder="请选择商品分类" :option="commodityCategorySelect"
                     @change-value="changeSelect"/>
        </div>
        <div class="commodity-search-item">
          <el-input v-model="name" placeholder="请输入商品名称或描述" clearable @keyup.enter="doSearch"/>
        </div>
        <!--        <div class="commodity-search-item">-->
        <!--          <el-input></el-input>-->
        <!--        </div>-->
        <div class="commodity-search-item">
          <el-button type="primary" @click="doSearch">搜 索</el-button>
        </div>
      </div>
      <div class="commodity-list-box">
        <template v-if="commodityList === null || commodityList.length === 0">
          <div class="commodity-none">
            <el-empty description="暂无商品"/>
          </div>
        </template>
        <template v-else>
          <scroll-box @scroll="handleSizeChangeScroll" :loading="loading">
            <div class="commodity-list-item" v-for="(commodity, index) in commodityList" :key="index">
              <CommodityInfo :data="commodity" @click-add="addShopping" @click-buy="buyThisCommodity"/>
            </div>
          </scroll-box>
        </template>
      </div>
    </div>
    <div class="shop-other">
      <move-to v-model="moveToShow" title="未登录" description="您未登录，是否跳转登录界面" url="/login?redirect=login"/>
    </div>
    <!--    <div class="shop-page" v-if="pageObj.totalCount > 0">-->
    <!--      <el-pagination-->
    <!--          v-model:current-page="pageObj.currentPage"-->
    <!--          v-model:page-size="pageObj.pageSize"-->
    <!--          :page-sizes="[20, 50, 100, 200]"-->
    <!--          size="default"-->
    <!--          background-->
    <!--          layout="total, sizes, prev, pager, next, jumper"-->
    <!--          :total="pageObj.totalCount"-->
    <!--          @size-change="handleSizeChange"-->
    <!--          @current-change="handleCurrentChange"-->
    <!--      />-->
    <!--    </div>-->
  </div>
</template>

<style scoped lang="scss">
.shop-box {
  position: relative;

  .right-tab {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: absolute;
    right: -35rem;
    top: 55rem;

    .right-tab-item {
      padding: 1rem 1rem;
      cursor: pointer;
      background-color: #d23d69;
    }
  }

  .shop-tab {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 2rem;
    padding: 1.5rem 0;
    background-color: #fff;
    user-select: none;

    .shop-tab-item {
      cursor: pointer;
    }

    .shop-tab-item-active {
      color: var(--text-active-color) !important;
    }

    .shop-tab-item:hover {
      color: var(--text-active-color);
    }
  }

  .shop-content {
    display: flex;
    flex-direction: column;
    //align-items: center;

    .commodity-search-box {
      display: flex;
      justify-content: center;
      padding: 2rem 1rem;

      .commodity-search-item {
        padding: 0 .5rem;
      }
    }

    .commodity-none {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    .commodity-list-box {
      display: flex;
      justify-content: start;
      flex-wrap: wrap; /* 允许子元素换行 */
      width: 100%;
    }
  }

  .shop-page {
    margin: 1rem 0;
  }
}
</style>